<?php

namespace App\Controller\AdminApi\Trade;

use App\Base\IRI;
use App\Base\BaseForm;
use App\Base\ActionBox\ActionBox;
use App\Base\SearchBox\SearchBox;
use App\Base\BaseController4Admin;
use App\Entity\Trade\ProductTrade;
use App\Repository\Lang\LangPackRepository;
use App\Repository\Trade\CategoryTradeRepository;
use Symfony\Component\Routing\Annotation\Route;

use App\Repository\Trade\ProductTradeRepository as Repository;
use App\Entity\Trade\ProductTrade as Entity;

/**
 * @Route("/admin/")
 */
class ProductTradeAdminApiController extends BaseController4Admin
{
    public $noDelete = [];
    public $entityName = "ProductTrade";
    public $limit = 10;
    public $listRow = ["id","lang.name","cat.name","pic","name","cut","useCut","isOn"];

    /**
     * @Route("ProductTrade/form",name="ProductTradeForm")
     */
    public function form(Repository $repository,CategoryTradeRepository $categoryTradeRepository,LangPackRepository $langPackRepository)
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]??0);
        $next = 0;
        $prev = 0;
        if (!$entity) {
            $entity = new Entity();
            $entity->setPics(["/userpics/001.jpg","/userpics/002.jpg","/userpics/002.jpg"]);
        }else{
            $qb = $repository->createQueryBuilder("A");
            createWhere($qb,["gt"=>["id"=>$data["id"]??0]]);
            $qb->setFirstResult(0)->setMaxResults(1);
            $qb->orderBy("A.id","ASC");
            $rst = $qb->getQuery()->execute();
            if (count($rst)==1) {
                if (isset($rst[0])) {
                    $next = $rst[0]->getId();
                }
            }
            $qb = $repository->createQueryBuilder("A");
            createWhere($qb,["lt"=>["id"=>$data["id"]??0]]);
            $qb->orderBy("A.id","DESC");
            $qb->setFirstResult(0)->setMaxResults(1);
            $rst = $qb->getQuery()->execute();
            if (count($rst)==1) {
                if (isset($rst[0])) {
                    $prev = $rst[0]->getId();
                }
            }
        }
        if (!$entity->getPics()) {
            $entity->setPics([]);
        }
        $BaseForm = new BaseForm(Entity::class);
        //表单选项
        $BaseForm->addSelect("lang","语言包",$langPackRepository->get4Choice())->getData();
        $BaseForm->addSelect("cat","分类目录",$categoryTradeRepository->getSons4Setting())->enableFind()->ruleNotNull()->getData();
        $BaseForm->addItem("name")->getData();
        $BaseForm->addPic("pic","图片")->getData();
        $BaseForm->addArrayText("price","价格")
            ->setLabel(["散装","打包","整箱"])
            ->setMod(false)
            ->setWidth(5)
            ->getData();
        $BaseForm->addItem("intro")->getData();
        $BaseForm->addItem("cut")->getData();
        $BaseForm->addItem("useCut")->getData();
        $BaseForm->addItem("isOn")->getData();
        $BaseForm->addItem("pics")->getData();

        $entity = $this->toArray($entity);
        if (!$entity["price"])$entity["price"] = ["","",""];
        $BaseForm->setEntity($entity);
        $data = array(
            "title" => "创建表单",
            "show"   => $BaseForm->createForm(),
            "isAdd"   => true,
            "next"   => $next,
            "prev"   => $prev,
        );
        return $this->json_out(1,"OK",$data);
    }

    /**
     * @Route("ProductTrade/submit",name="ProductTradeSubmit",methods={"POST"})
     */
    public function submit(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]?:0);
        if (!$entity) {$entity = new  Entity();}
        /**@var $ProductTrade Entity*/
        $ProductTrade = $this->updateEntity($data,Entity::class,$entity);
        $this->myEm()->persist($ProductTrade);$this->myEm()->flush();
        return $this->json_out(1,"保存成功","/admin/list/auto?en=".$this->entityName);
    }

    /**
     * @Route("ProductTrade/list",name="ProductTradeGetList")
     */
    public function getList(Repository $repository,LangPackRepository $langPackRepository,CategoryTradeRepository $categoryTradeRepository)
    {
        $this->needToBeAdmin();
        $data       = $this->getRequestData();
        $per_page   = $this->limit;
        $page       = $data["page"]??1;
        $where      = $data['_where']??[];
        $search     = $data['_search']??[];
        $order      = $data["_order"]??[];

        //列表筛选
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
        $this->setGroups("lang","prod","cat");
        $list= $this->normalize($list);

        //列表计数
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        //表头数据和列表内展示形式
        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);
        //额外数据示例
        //$config["KEY"] = (new Common())->setName("NAME")->setWidth("300");

        $lang = null;
        if (isset($where["eq"])) {
            $lang = $where["eq"]["lang"]?:null;
        }
        //设置筛选数据表单
        $sb = new SearchBox();
        $sb->setExcel(false);
        $sb->addSelect("lang")->setChoices($langPackRepository->get4Choice(true))
            ->setHelpText("所属语言")->createData();
        $sb->addSelect("cat")->setChoices($categoryTradeRepository->get4Choice($lang))
            ->setHelpText("商品分类")->createData();
        $sb->addText("name")->setHelpText("品名");


        //设置筛选数据表单
        $ab = new ActionBox();
        $ab->addSelect("lang")->setChoices($langPackRepository->get4Choice())->setHelpText("所属语言")->createData();
        $ab->addSelect("cat")->setChoices($categoryTradeRepository->get4Choice($lang))->setHelpText("所属语言")->createData();
        $ab->addSelect("useCut")->setChoices(CHOICE_IS_TRUE)->setHelpText("使用商品折扣")->createData();
        $ab->addSelect("isOn")->setChoices(CHOICE_IS_TRUE)->setHelpText("上架")->createData();
        $ab->addText("cut")->setHelpText("折扣率（%）");

        $data = array(
            'en'     => "{$this->entityName}",
            'title'     => "列表",
            'header'     => $this->listRow,
            "config"    => $config,
            'lists'     => $list,
            'searchBox' => $sb->createData(),
            'actionBox' => $ab->createData(),
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }

    /**
     * @Route("ProductTrade/excel",name="ProductTradeGetListExcel")
     */
    public function getListExcel(Repository $repository)
    {
        $this->needToBeAdmin();
        $data       = $this->getRequestData();
        $where      = $data['_where']??[];
        $search     = $data['_search']??[];
        $order      = $data["_order"]??[];
        //列表筛选
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $list = $qb->getQuery()->execute();
        $list= $this->normalize($list);

        $config = getEntityAnnotationData(Entity::class);
        if (count($list)>0) {
            $row = $list[0];
            $title = [];
            foreach ($row as $key=>$value) {
                $title[] = isset($config[$key])?$config[$key]->cnName:"";
            }
        }else{
            $title=[
                "","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
            ];
        }
        $this->excelOut($title,$list,"123.xls");
    }


    /**
     * @Route("ProductTrade/delete",name="ProductTradeDelete",methods={"POST"})
     */
    public function delete(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $ids = $this->getRequestData()["ids"]??[];
        foreach ($ids as $id) {
            if (in_array($id , $this->noDelete) || in_array(0 , $this->noDelete)) {continue;}
            if ($entity= $repository->find($id)) {$this->myEm()->remove($entity);}
        }
        $this->myEm()->flush();
        return $this->json_out(1,'删除成功');
    }


    /**
     * @Route("ProductTrade/action",name="ProductTradeAction",methods={"GET","POST"})
     */
    public function UserAction(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $ids = $this->getRequestData()["ids"]??[];
        $action = $this->getRequestData()["_action"]??[];
        //移除没有值的项
        foreach ($action as $key=>$value) {
            if ($value === "") {
                unset($action[$key]);
            }
        }
        foreach ($ids as $id) {
            if ($entity= $repository->find($id)) {
                $entity = $this->updateEntity($action,Entity::class,$entity);
                $this->myEm()->persist($entity);
            }
        }
        $this->myEm()->flush();
        return $this->json_out(1,'修改成功');
    }

    /**
     * @Route("ProductTrade/copy",name="ProductTradeCopy")
     */
    public function doCopy(Repository $repository)
    {
        $data = $this->getRequestData();
        if (!$entity = $repository->find($data["id"]??0)) {
            return $this->json_out(0,"数据丢失");
        }
        $tmp = $entity;
        $tmp = $this->toArray($tmp);
        $en = $this->serializer->denormalize($tmp,Entity::class);
        $this->myEm()->persist($en);$this->myEm()->flush();
        return $this->json_out(1,"复制成功");
    }


    /**
     * 用于entity组件窗口选择器
     * @Route("ProductTrade/search",name="ProductTradeGetList4EntitySelect")
     */
    public function getList4EntitySelect(Repository $repository)
    {
        $this->needToBeAdmin();
        $data = $this->getRequestData();
        $page = $data["page"]??1;
        $per_page   = $this->limit;
        $where = $data['_where']??[];
        $search = $data['_search']??[];
        $order = $data["_order"]??[];

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
        $list= $this->normalize($list);

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);
        $data = array(
            'en'     => "{$this->entityName}",
            'title'     => "列表",
            'header'     => ["id","name"],
            "config"    => $config,
            'lists'     => $list,
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }


    /**
     * 用于ENTITY组件选项关展示
     * @Route("ProductTrade/viewer",name="ProductTradeList4EntityViewer")
     */
    public function ProductTradeList4EntityViewer(Repository $repository)
    {
        $data = $this->getRequestData();
        $id = $data["id"]??0;
        if (!is_array($id)) {
            $id = [$id];
        }
        $re = [];
        foreach ($id as $v) {
            //分别分成iri 和 id 两种方式
            $arr = myExplodeNumbers($v);
            $realId = array_pop($arr);
            $en = $repository->find($realId);
            if (!$en) {continue;}
            $re[] = [
                "id" => $en->getId(),
                "val" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }

    /**
     * 用于列表组件List
     * @Route("ProductTrade/choice",name="ProductTradeList4ListChoice")
     */
    public function ProductTradeList4ListChoice(Repository $repository)
    {
        $all = $repository->findBy(array());
        foreach ($all as $en) {
            $re[] = [
                "id" => IRI::createIRIStringFromEntity(Entity::class,$en->getId()),
                "value" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }


    /**
     * excel导入
     * @Route("ProductTrade/import/form",name="ProductTradeImportForm")
     */
    public function ProductTradeImportForm(Repository $repository)
    {
        $BaseForm = new BaseForm(Entity::class);
        //表单选项

        $BaseForm->addFile("file","文件")->getData();

        $entity = [];
        $entity["file"] = '';
        $BaseForm->setEntity($entity);
        $data = array(
            "title" => "创建表单",
            "show"   => $BaseForm->createForm(),
            "isAdd"   => true,
            "next"   => 0,
            "prev"   => 0,
        );
        return $this->json_out(1,"OK",$data);
    }
    /**
     * excel导入
     * @Route("ProductTrade/import",name="ProductTradeImport")
     */
    public function ProductTradeImport(Repository $repository,CategoryTradeRepository $categoryTradeRepository,LangPackRepository $langPackRepository)
    {
        $req = $this->getRequestData();
        $file = $req['file']??["name"=>"","file"=>""];

        if ($path = $file["file"]) {
            $data = $this->excelRead($path);

            foreach ($data as $row) {
                $prod = new ProductTrade();
                $cat = $categoryTradeRepository->findOneBy(array('id'=>$row[8]));
                $prod->setName($row[0])
                    ->setPrice([$row[1],$row[2],$row[3]])
                    ->setPic("/userpics/ftp/".$row[4])
                    ->setCut($row[5])
                    ->setUseCut($row[6])
                    ->setIntro($row[7])
                    ->setCat($cat)
                    ->setLang($langPackRepository->find($row[9]))
                    ->setPics([])
                    ->setIsOn(false)
                ;
                $this->myEm()->persist($prod);
            }
            $this->myEm()->flush();

            return $this->json_out(1,"OK",$data);
        }else{
            return $this->json_out(0,"请选择文件",$file);
        }

    }




}
